﻿#include "xList.h"
#include <string.h>
#include <stdlib.h>

typedef struct _XLIST_NODE {
	struct _XLIST_NODE* pre;
	struct _XLIST_NODE* next;
} XLIST_NODE;

static int xlist_insert(struct _xlist_* thes, void* e) {
    char* _acd_pc = (char*)malloc(sizeof(XLIST_NODE) + thes->item_size);
    XLIST_NODE* it = (XLIST_NODE*)_acd_pc;
    XLIST_NODE* ph = (XLIST_NODE*)thes->ptr;
    XLIST_NODE* ptail = ph->pre;
    memcpy(_acd_pc + sizeof(XLIST_NODE), e, thes->item_size) ;

	ptail->next = it;
	it->next = ph;
	it->pre = ptail;
	ph->pre = it;
	thes->cnt++;
	return 0;
}

static int xlist_erase(struct _xlist_* thes, XListIterator* it) {
	XLIST_NODE* e = (XLIST_NODE*)it->ptr;
	if (thes->ptr == it->ptr) return -1;
	e->next->pre = e->pre;
	e->pre->next = e->next;
	it->ptr = e->pre;
	free(e);
	thes->cnt--;
	return 0;
}

static void* xlist_begin(struct _xlist_* thes) {
	return ((XLIST_NODE*)thes->ptr)->next;
}

static void* xlist_end(struct _xlist_* thes) {
	return thes->ptr;
}

static int xlist_release(struct _xlist_* thes) {
	XLIST_NODE* ph = thes->ptr;
	XLIST_NODE* pIt = ph->next;

	while(ph != pIt) {
		XLIST_NODE* pTmp = pIt->next;
		free(pIt);
		pIt = pTmp;
	}
	free(ph);
	thes->ptr = 0;
	thes->cnt = 0;
	return 0;
}

int construct_xlist(XList* thes, int item_size) {
	XLIST_NODE* ph = (XLIST_NODE*)malloc(sizeof(XLIST_NODE));
	ph->next = ph;
	ph->pre = ph;
	thes->ptr = ph;
	thes->item_size = item_size;
	thes->cnt = 0;

	thes->insert = xlist_insert;
	thes->erase = xlist_erase;
	thes->begin = xlist_begin;
	thes->end = xlist_end;
	thes->release = xlist_release;
	return 0;
}

static void* xlist_iterator_next(struct _xlist_itorator* thes) {
	thes->ptr = ((XLIST_NODE*)thes->ptr)->next;
	return thes->ptr;
}

int construct_clist_iterator(XListIterator* thes) {
	thes->ptr = 0;
	thes->next = xlist_iterator_next;
	return 0;
}







